<template>
  <div class="student-management">
    <el-card>
      <template #header>
        <div class="card-header">
          <div class="header-left">
            <el-button @click="goBack" type="info" plain>
              <el-icon><ArrowLeft /></el-icon>
              返回班级列表
            </el-button>
            <span class="clazz-name">{{ clazzName }} - 学生管理</span>
          </div>
          <div class="header-actions">
            <span class="welcome-text">欢迎，{{ username }}</span>
            <el-button type="primary" @click="handleAdd">
              <el-icon><Plus /></el-icon>
              新增学生
            </el-button>
            <el-button @click="handleLogout"> 退出登录 </el-button>
          </div>
        </div>
      </template>

      <!-- 搜索栏 -->
      <div class="search-bar">
        <el-input
          v-model="searchKeyword"
          placeholder="请输入学生姓名搜索"
          style="width: 300px"
          clearable
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
        <el-button type="primary" @click="handleSearch">搜索</el-button>
        <el-button @click="handleReset">重置</el-button>
      </div>

      <!-- 表格 -->
      <el-table
        :data="tableData"
        v-loading="loading"
        style="width: 100%; margin-top: 20px"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="学生姓名" />
        <el-table-column prop="gender" label="性别" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.gender === '男' ? 'primary' : 'danger'">
              {{ scope.row.gender }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="clazz_id" label="班级ID" width="100" />
        <el-table-column prop="created_at" label="创建时间" width="200">
          <template #default="scope">
            {{ formatDate(scope.row.created_at) }}
          </template>
        </el-table-column>
        <el-table-column prop="updated_at" label="修改时间" width="200">
          <template #default="scope">
            {{ formatDate(scope.row.updated_at) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.row)"
              >编辑</el-button
            >
            <el-button
              size="small"
              type="danger"
              @click="handleDelete(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[5, 10, 20, 50]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑学生' : '新增学生'"
      width="500px"
    >
      <el-form :model="form" :rules="rules" ref="formRef" label-width="80px">
        <el-form-item label="学生姓名" prop="name">
          <el-input v-model="form.name" placeholder="请输入学生姓名" />
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-select
            v-model="form.gender"
            placeholder="请选择性别"
            style="width: 100%"
          >
            <el-option label="男" value="男" />
            <el-option label="女" value="女" />
          </el-select>
        </el-form-item>
        <el-form-item label="班级ID" prop="clazz_id">
          <el-input v-model="form.clazz_id" placeholder="班级ID" readonly />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search, ArrowLeft } from '@element-plus/icons-vue'
import { studentApi } from '../api/student.js'

const router = useRouter()
const route = useRoute()

// 响应式数据
const loading = ref(false)
const tableData = ref([])
const searchKeyword = ref('')
const currentPage = ref(1)
const pageSize = ref(5)
const total = ref(0)
const username = ref(localStorage.getItem('username') || '')
const clazzId = ref(route.params.id)
const clazzName = ref(decodeURIComponent(route.query.clazzName || ''))

// 对话框相关
const dialogVisible = ref(false)
const isEdit = ref(false)
const formRef = ref()

// 表单数据
const form = reactive({
  id: null,
  name: '',
  gender: '',
  clazz_id: clazzId.value
})

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入学生姓名', trigger: 'blur' },
    { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
  ],
  gender: [{ required: true, message: '请选择性别', trigger: 'change' }]
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '-'
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN')
}

// 获取学生列表
const getStudentList = async () => {
  loading.value = true
  try {
    const params = {
      pageIndex: currentPage.value,
      pageSize: pageSize.value,
      clazzId: clazzId.value
    }
    if (searchKeyword.value) {
      params.keyword = searchKeyword.value
    }

    const response = await studentApi.getList(params)
    if (response.data.code === 0) {
      tableData.value = response.data.data.rows || []
      total.value = response.data.data.count || 0
    } else {
      ElMessage.error(response.data.msg || '获取数据失败')
    }
  } catch (error) {
    console.error('获取学生列表失败:', error)
    ElMessage.error('获取数据失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  getStudentList()
}

// 重置
const handleReset = () => {
  searchKeyword.value = ''
  currentPage.value = 1
  getStudentList()
}

// 返回班级列表
const goBack = () => {
  router.push('/class-management')
}

// 新增
const handleAdd = () => {
  isEdit.value = false
  form.id = null
  form.name = ''
  form.gender = ''
  form.clazz_id = clazzId.value
  dialogVisible.value = true
}

// 编辑
const handleEdit = (row) => {
  isEdit.value = true
  form.id = row.id
  form.name = row.name
  form.gender = row.gender
  form.clazz_id = row.clazz_id
  dialogVisible.value = true
}

// 删除
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(`确定要删除学生"${row.name}"吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    const response = await studentApi.delete(row.id)
    if (response.data.code === 0) {
      ElMessage.success('删除成功')
      getStudentList()
    } else {
      ElMessage.error(response.data.msg || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除学生失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()

    if (isEdit.value) {
      // 编辑
      const response = await studentApi.update(form.id, {
        name: form.name,
        gender: form.gender,
        clazz_id: form.clazz_id
      })
      if (response.data.code === 0) {
        ElMessage.success('更新成功')
        dialogVisible.value = false
        getStudentList()
      } else {
        ElMessage.error(response.data.msg || '更新失败')
      }
    } else {
      // 新增
      const response = await studentApi.create({
        name: form.name,
        gender: form.gender,
        clazz_id: form.clazz_id
      })
      if (response.data.code === 0) {
        ElMessage.success('添加成功')
        dialogVisible.value = false
        getStudentList()
      } else {
        ElMessage.error(response.data.msg || '添加失败')
      }
    }
  } catch (error) {
    console.error('提交表单失败:', error)
    ElMessage.error('操作失败')
  }
}

// 分页相关
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
  getStudentList()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  getStudentList()
}

// 退出登录
const handleLogout = () => {
  localStorage.removeItem('token')
  localStorage.removeItem('username')
  window.location.href = '/login'
}

// 组件挂载时获取数据
onMounted(() => {
  getStudentList()
})
</script>

<style scoped>
.student-management {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 15px;
}

.clazz-name {
  font-size: 18px;
  font-weight: bold;
  color: #409eff;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 15px;
}

.welcome-text {
  color: #666;
  font-size: 14px;
}

.search-bar {
  display: flex;
  align-items: center;
  gap: 10px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>
